<template>
  <!--  传感器信息管理页面-->
  <div class="page">
    <!-- 条件筛选 -->
    <div class="page_filter">
      <el-input v-model="form.code" clearable placeholder="请输入传感器编号">
        <template slot="prepend">传感器编号</template>
      </el-input>
      <el-input v-model="form.batch" clearable placeholder="请输入传感器批次号">
        <template slot="prepend">批次号</template>
      </el-input>
      <el-select v-model="form.type" @change="sensorTypeChange" clearable placeholder="请选择传感器类型">
        <el-option v-for="item in EnumSensorTypeList" :key="item.code" :label="item.name" :value="item.code">
        </el-option>
      </el-select>
      <el-select v-model="form.modelId" clearable placeholder="请选择传感器型号">
        <el-option v-for="item in modelSearch" :key="item.id" :label="item.name" :value="item.id">
        </el-option>
      </el-select>
      <el-button class="common_btn-defalut" icon="el-icon-search" @click="form.page=1;queryList()">搜索</el-button>
    </div>
    <div class="page_main">
      <!-- table -->
      <div class="common_btnBox" >
        <i class="iconfont iconzongshu icon-size"></i>
        总数：{{form.total}}
      </div>
      <el-table :data="tableList" border>
        <el-table-column label="序号" fixed width="80">
          <template slot-scope="scope">
            {{getIndex(scope.$index)}}
          </template>
        </el-table-column>
        <el-table-column prop="code" sortable show-overflow-tooltip label="编号" min-width="165"></el-table-column>
        <el-table-column prop="batch" sortable show-overflow-tooltip label="批次" width="100"></el-table-column>
        <el-table-column prop="sn" sortable label="采集仪SN" min-width="165"></el-table-column>
        <el-table-column prop="typeName" sortable label="类型" min-width="150"></el-table-column>
        <el-table-column prop="operator" label="操作人" width="120"></el-table-column>
        <el-table-column prop="createTime" sortable label="创建时间" width="180">
          <template slot-scope="scope">
            {{scope.row.createTime|formatTimer()}}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" sortable label="更新时间" width="180">
          <template slot-scope="scope">
            {{scope.row.updateTime|formatTimer()}}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" min-width="220">
          <template slot-scope="scope">
            <span v-if="scope.row.type === 1">
               <el-button type="text" class="btn_add" @click="paramImport(scope.row.code)">导入参数</el-button>
            <el-button type="text" class="btn_edit" @click="paramDownload(scope.row.code)">查看参数</el-button>
               <el-button type="text" class="btn_add"
                          @click="compensateParamDownloads(scope.row)">补偿参数</el-button>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="form.page"
                     :page-size="form.pageSize"    :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
              layout="sizes, prev, pager, next"  :total="form.total">
      </el-pagination>
    </div>
    <!-- 参数导入 -->
    <el-dialog title="重力加速度计参数导入" :visible.sync="isShowImportDialog" :close-on-click-modal="false" width="520px">
      <div style="text-align: center;font-size: 20px;color: #ff4d51;margin-bottom: 20px">{{formImport.code}}</div>
      <el-form label-position="right" ref="formImport" :rules="rulesImport" :model="formImport" label-width="130px">
        <el-form-item label="上传CLIB文件" prop="clibFileName">
          <el-input v-model="formImport.clibFileName" :readonly='true' placeholder="如：CXB01_CLIB.mat">
            <template slot="append">
              <el-upload class="upload-demo" ref="upload" action="doUpload" :limit="1" :file-list="files"
                         :before-upload="beforeUpload">
                <el-button slot="trigger" type="primary" plain>选取参数文件</el-button>
              </el-upload>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="上传COMP文件" prop="compFileName">
          <el-input v-model="formImport.compFileName" :readonly='true' placeholder="如：CXB01_TEMP_COMP.mat">
            <template slot="append">
              <el-upload class="upload-demo" ref="upload" action="doUpload" :limit="1" :file-list="files"
                         :before-upload="beforeUpload2">
                <el-button slot="trigger" type="primary" plain>选取参数文件</el-button>
              </el-upload>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button class="common_btn-white" @click="isShowImportDialog = false" type="info">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="validateImportForm">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="paramDialogTitle" :visible.sync="showParamDialog" :close-on-click-modal="false" width="520px">
      <el-input
        type="textarea"
        :rows="25"
        v-model="paramContent">
      </el-input>
      <!-- 操作按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button class="common_btn-defalut" type="primary" @click="showParamDialog = false">确定</el-button>
      </span>
    </el-dialog>
    <!--  补偿参数-->
    <el-dialog title="补偿参数" :visible.sync="compensateParamDownload" :close-on-click-modal="false"
               width="520px">
      <el-form label-position="right" ref="formCompensate" :model="currentRow" :rules="compensateRules"
               label-width="200px">
        <el-form-item label="倾角温度补偿系数K" prop="angleK">
          <el-input v-model="currentRow.angleK" placeholder="" type="number">
          </el-input>
        </el-form-item>
        <el-form-item label="倾角温度补偿系数B" prop="angleB">
          <el-input v-model="currentRow.angleB" placeholder="" type="number">
          </el-input>
        </el-form-item>
      </el-form>
      <!-- 操作按钮 -->
      <span slot="footer" class="dialog-footer">
         <el-button class="common_btn-white" @click="compensateParamDownload = false;currentRow= {
          holePosition: '1',
          angleK: '',
          angleB: '',
        }" type="info">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="validatecompensateForm">确定</el-button>

      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    sensorQuery,
    sensorDelete,
    sensorAdd,
    sensorUpdate,
    sensorParamAddMat,
    getEquipType,
    sensorParamDownload
  } from '@/services/model/sensor'
  import Enums from '@/utils/enums'
  import Format from '@/utils/format'
  const RULESIMPORT = {
    clibFileName: {
      required: true,
      message: '请上传CLIB文件'
    },
    compFileName: {
      required: true,
      message: '请上传COMP文件',
    },
  }
  const COMPENSATERULES = {
    angleK: {
      required: true,
      message: '请输入倾角温度补偿系数K'
    },
    angleB: {
      required: true,
      message: '请输入倾角温度补偿系数B',
    },
  }
  export default {
    mixins:[Enums],
    data() {
      return {
        paramContent: '',
        form: {
          page: 1,
          pageSize: 10,
          total: 0,
        },
        rulesImport: RULESIMPORT, // 表单校验的规则
        compensateRules: COMPENSATERULES,// 表单校验的规则
        tableList: [],
        showParamDialog: false, // 是否显示弹窗
        compensateParamDownload: false,
        isShowImportDialog: false, // 是否显示参数导入弹窗
        currentRow: {
          holePosition: '1',
          angleK: '',
          angleB: '',

        }, // 新增数据
        EnumSensorTypeList: [],
        modelOptions: [],
        modelSearch: [],
        compensateImportImport: {},
        formImport: {
          clibFileName: '',
          compFileName: '',
          clibFile: null,
          compFile: null,
        },
        files: [],
        paramDialogTitle: '',
      }
    },
    computed: {
      // 弹窗的title
      dialogTitle() {
        return this.currentRow.id ? '编辑传感器信息' : '新增传感器信息'
      },
    },
    filters: {
      // 时间格式化
      formatTimer(timer) {
        return Format(new Date(timer))
      },
    },
    methods: {
      async paramDownload(code) {
        let res = await sensorParamDownload({code: code})
        this.paramContent = res.data || ''
        this.showParamDialog = true
        this.paramDialogTitle = code + '参数信息'
      },
      async compensateParamDownloads(row) {
        this.currentRow.angleB=row.angleB
        this.currentRow.angleK=row.angleK
        this.currentRow.id = row.id
        this.compensateParamDownload = true

      },
      async sensorTypeChange(val) {
        let res = await getEquipType({sensorType: val});
        this.modelSearch = res.data ? res.data : []
      },
      async sensorTypeChange2(val) {
        let res = await getEquipType({sensorType: val});
        this.modelOptions = res.data ? res.data : []
        this.$set(this.currentRow, "modelId", "");
      },
      beforeUpload(file) { // 上传前 文件校验
        this.formImport.clibFile = null
        this.formImport.clibFileName = ''
        const extension = file.name.split('.')[1] === 'mat'
        const type = file.name.split('_')[1]
        const isLt2M = file.size / 1024 / 1024 < 1
        if (!extension) {
          this.$message.warning('上传文件只能是 mat格式!')
          return
        }
        if (type !== 'CLIB.mat') {
          this.$message.warning('请上传*_CLIB文件')
          return
        }
        if (!isLt2M) {
          this.$message.warning('上传文件大小不能超过 1MB!')
          return
        }
        this.formImport.clibFile = file
        this.formImport.clibFileName = file.name
        return false // 返回false不会自动上传
      },
      beforeUpload2(file) { // 上传前 文件校验
        this.formImport.compFile = null
        this.formImport.compFileName = ''
        const extension = file.name.split('.')[1] === 'mat'
        const type = file.name.split('_')[2]
        const isLt2M = file.size / 1024 / 1024 < 1
        if (!extension) {
          this.$message.warning('上传文件只能是 mat格式!')
          return
        }
        if (type !== 'COMP.mat') {
          this.$message.warning('请上传*_TEMP_COMP文件')
          return
        }
        if (!isLt2M) {
          this.$message.warning('上传文件大小不能超过 1MB!')
          return
        }
        this.formImport.compFile = file
        this.formImport.compFileName = file.name
        return false // 返回false不会自动上传
      },

      // 获取当前的序号
      getIndex(index) {
        let param = (this.form.page - 1) * this.form.pageSize + index + 1
        return param
      },
      // 分页大小改变
      handleSizeChange(val) {
        this.form.pageSize = val
        this.queryList()
      },
      // 当前页码改变
      handleCurrentChange(val) {
        this.form.page = val
        this.queryList()
      },
      // 表单提交
      validateForm() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.submitData()
          }
        })
      },
      //补偿参数提交
      validatecompensateForm() {
        this.$refs.formCompensate.validate((valid) => {
          if (valid) {
            this.compensateUpdate()
          }
        })
      },
      async compensateUpdate() {
        let res = await sensorUpdate(this.currentRow)
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: this.currentRow.id ? '编辑成功' : '添加成功'
          })
          this.currentRow = {
            holePosition: '1',
            angleK: '',
            angleB: '',

          },
            this.compensateParamDownload = false
          this.queryList()
        }
      },
      validateImportForm() {
        this.$refs.formImport.validate((valid) => {
          if (valid) {
            this.submitParamFile()
          }
        })
      },
      async submitParamFile() {
        let fileFormData = new FormData()
        if (this.formImport.clibFile && this.formImport.compFile) {
          fileFormData.append('uploadFile', this.formImport.clibFile, this.formImport.clibFileName) // 上传的文件
          fileFormData.append('uploadFile', this.formImport.compFile, this.formImport.compFileName) // 上传的文件
          fileFormData.append('code', this.formImport.code) // 上传的文件
          sensorParamAddMat(fileFormData).then(res => { // 上传请求
            if (res.code === 200) {
              this.$notify({
                type: 'success',
                title: '提示',
                message: '参数导入成功！'
              })
              this.formImport.clibFile = ''
              this.formImport.compFile = ''
              this.formImport.clibFileName = ''
              this.formImport.compFileName = ''
              this.isShowImportDialog = false
            }
          })
        }
      },
      // 处理删除
      async handleDelete(row) {
        let res = await sensorDelete({
          id: row.id
        })
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: '数据已删除'
          })
          this.queryList()
        }
      },
      /**
       * row  参数导入
       */
      paramImport(code) {
        this.formImport = {
          code: code,
          clibFileName: '',
          compFileName: '',
          clibFile: null,
          compFile: null,
        }
        this.isShowImportDialog = true
        this.$nextTick(() => {
          this.$refs.formImport.clearValidate()
        })
      },
      async queryList() {
        let res = await sensorQuery(this.form)
        this.tableList = res.data?.records || []
        this.form.page = Number(res.data?.current)
        this.form.total = Number(res.data?.total)

      },
    },
    mounted() {
      //	传感器类型下拉框
      this.queryDictList(['EnumSensorType'], ['EnumSensorTypeList'])
    },
    activated() {
      this.queryList()
    }
  }
</script>

<style lang="less" scoped>
</style>
